package com.gujiangbo.sentinel.controller;

import com.alibaba.csp.sentinel.AsyncEntry;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.gujiangbo.sentinel.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsyncHelloController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("async")
    public void sayHello() {
        //限流开始
        AsyncEntry asyncEntry = null;
        try {
            asyncEntry = SphU.asyncEntry("Sentinel_Async");//限流入口
            asyncService.hello();
        } catch (BlockException e) {
            System.out.println("系统繁忙，稍后再试！！！！！");
        } finally {
            if (asyncEntry != null) {
                asyncEntry.exit();
            }
        }
    }

    /**
     * 自定义限流规则
     */
/*    @PostConstruct//当前类的构造函数执行完毕之后再执行的方法
    public void initFlowRules() {
        //1.创建限流规则集合
        List<FlowRule> rules = new ArrayList<FlowRule>();
        //2.创建限流规则
        FlowRule flowRule = new FlowRule();
        //定义资源，标识Sentinel对哪个资源生效
        flowRule.setResource("Sentinel_Async");
        //定义限流规则类型,QPS
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //QPS设置限流值,每秒通过的请求个数
        flowRule.setCount(2);
        //3.将限流规则存放到集合中
        rules.add(flowRule);
        //4.加载限流规则
        FlowRuleManager.loadRules(rules);
    }*/
}
